<template>
  <div class="main">
    <div class="header">
      <div class="search default">
        <!-- <el-button type="primary" size="mini" @click='updateMaterialDownload'>更新材料</el-button> -->
        <!-- <div class="def">分类筛选:</div>
        <el-select style="margin:0 10px" v-model="category.selectValue" filterable clearable placeholder="请选择分类">
          <el-option v-for="item in category.list" :key="item.classificationId" :label="item.name" :value="item.value">
          </el-option>
        </el-select> -->
        <!-- <div class="default">
          <el-button type="primary" @click="searchCateInfo">查询</el-button>
        </div> -->
      </div>
      <div class="flex">
        <el-button @click="createCate" size='small'>新增分类</el-button>
        <div class="default">
          <el-button type="primary" @click="edifMaterail('add')" size='small' color="#ff6a00">新增材料</el-button>
        </div>
      </div>
    </div>
    <!-- 分类材料列表   -->
    <div class="mainTable">
      <el-table :height="maxHeight + 'px'"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      v-loading="loading" :data="material.list" border style="width: 100%"
        :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400','background':'#ff6a00','color':'white' }" :cellStyle="{ 'textAlign': 'center' ,'fontSize': '12px'}">
        <el-table-column type="expand"  label="展开" width="50px">
          <template slot-scope="props">
            <el-table :data="props.row.materials" stripe style="width: 100%"
              :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400' }" :cellStyle="{ 'textAlign': 'center','fontSize': '12px' }">
              <el-table-column prop="materialId" label="编码" min-width="100">
              </el-table-column>
              <el-table-column prop="materialName" label="名称" min-width="280">
              </el-table-column>
              <el-table-column prop="norm" label="规格" min-width="100">
              </el-table-column>
              <el-table-column prop="color" label="颜色" min-width="100">
              </el-table-column>
              <el-table-column prop="unit" label="单位" min-width="100">
              </el-table-column>
              <!-- <el-table-column prop="totalCount" label="库存" width="100">
              </el-table-column> -->
              <el-table-column prop="storeAverageUseCount" label="单店用量" min-width="100">
              </el-table-column>
              <!-- <el-table-column prop="storeInventoryCount" label="可用店铺数量" min-width="120">
                <template slot-scope="scope">
                  {{ (scope.row.totalCount / scope.row.storeAverageUseCount).toFixed(0) }}
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="storeInventoryCount" label="库存状态" min-width="100">
                <template slot-scope="scope">
                  <el-tag type="success"
                    v-if="scope.row.totalCount / scope.row.storeAverageUseCount > scope.row.storeInventoryCount">库存充足</el-tag>
                  <el-tag type='danger' v-else>库存告急</el-tag>
                </template>
              </el-table-column> -->
              <el-table-column prop="price" label="成本价" min-width="100" v-if="userName !=='GX'">
              </el-table-column>
              <el-table-column prop="salePrice" label="销售价" min-width="100" v-if="userName !=='GX'">
              </el-table-column>
              <el-table-column label="操作" fixed='right' min-width="180px">
                <template slot-scope="scope">
                  <el-button size="small" @click="edifMaterail('update', scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click='deleteMaterail(scope.row)'>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="name" min-width="200px"></el-table-column>
        <el-table-column label="创建时间" prop="createdAt" min-width="100px"></el-table-column>
        <!-- <el-table-column label="总库存" prop="totalCount" min-width="200px"></el-table-column> -->
        <el-table-column label="单位"  min-width="200px">
          <template slot-scope="scope">
            <div v-if="scope.row.largeUnit">{{scope.row.largeUnit}}</div>
            <div v-else>当前分类暂无材料，默认(件)</div>
          </template>
        </el-table-column>
        <el-table-column label="供应商" prop="supplierList" min-width="200px"></el-table-column>
        <!-- <el-table-column label="可用店铺数量" min-width="200px">
          <template slot-scope="scope">
            <el-tag type="success" v-if='scope.row.storeCount > 10'>
            可用店铺{{scope.row.storeCount}}家
            </el-tag>
          <el-tag type='danger' v-else>可用店铺小于10家</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="80px">
          <template slot-scope="scope">
            <el-link type='warning' @click="eidtCate(scope.row)">修改分类</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style='margin-top:20px' align="right" @size-change="handleMateSizeChange"
        @current-change="handleMateCurrentChange" :current-page="material.currentPage" :page-sizes="[20,30,40,50]"
          layout="total, sizes, prev, pager, next, jumper" :total="material.count">
      </el-pagination>
    </div>
    <!-- 新增分类弹窗 -->
    <el-dialog title="分类数据"  :visible.sync="category.cateVisible" width="70%">
      <div>
        <el-input v-model="category.createCateValue" placeholder="请输入新增分类名称">
          <el-button slot="append" type="primary" @click="createCateSend">新增</el-button>
        </el-input>
      </div>
      <div style="margin:10px 0;">
        <el-table :data="category.list" border style="width: 100%" :headerCellStyle="{ 'textAlign': 'center' }"
          :cellStyle="{ 'textAlign': 'center','fontSize': '12px' }">
          <el-table-column prop="classificationId" label="ID" width="80">
          </el-table-column>
          <el-table-column prop="name" label="分类名称" min-width="180">
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
          </el-table-column>
          <el-table-column label="操作" width="80px">
            <template slot-scope="scope">
              <el-link type="danger" @click="deleteCate(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination align="center" @size-change="handleCateSizeChange" @current-change="handleCateCurrentChange"
        :current-page="category.currentPage" :page-sizes="[5, 10]"
        layout="total, sizes, prev, pager, next, jumper" :total="category.count">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="category.cateVisible = false">取 消</el-button>
        <el-button type="primary" @click="cateClose">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改分类名称" :visible.sync="material.cateUpdateVisible" width="20%">
      <el-input v-model="material.cateUpdateValue"> </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="material.cateUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendEditCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改/新增材料 -->
    <el-dialog :title="type == 'add' ? '新增材料信息' : ' 修改材料信息'" :visible.sync="openMateStatuts" width="40%">
      <el-form ref="form" :model="rule" :rules="rules" label-width="80px">
        <el-form-item label="材料名称" requierd>
          <el-input v-model="rule.materialName"></el-input>
        </el-form-item>
        <el-form-item label="材料编码">
          <el-input v-model="rule.materialId" :disabled="isUpdate"></el-input>
        </el-form-item>
        <el-form-item label="材料属性">
          <div class="flex">
            <el-input v-model="rule.norm" clearable>
              <template slot="prepend">规格</template>
            </el-input>
            <el-input v-model="rule.color" clearable>
              <template slot="prepend">颜色</template>
            </el-input>
            <el-input v-model="rule.unit" clearable>
              <template slot="prepend">单位</template>
            </el-input>
            <el-input type="number" v-model="rule.storeAverageUseCount" clearable>
              <template slot="prepend">单店用量</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="材料供应" requierd>
          <div class="flex" style="grid-template-columns: repeat(2,1fr);">
            <el-select @change='editCateSelect' filterable v-model="rule.classificationId" clearable placeholder="请选择材料分类">
              <el-option v-for="item in  searchCateList" :key="item.classificationId" :label="item.name"
                :value="item.classificationId">
              </el-option>
            </el-select>
            <el-select @change='editSupplierSelect' filterable v-model="rule.supplierId" clearable placeholder="请选择供应商">
              <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
              :disabled="item.status !== 1"
                :value="item.supplierId">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="价格设置">
          <div class="flex" style="grid-template-columns: repeat(2,1fr);">
            <el-input v-model="rule.price" type="number"  clearable>
              <template slot="prepend">成本价</template>
            </el-input>
            <el-input v-model="rule.salePrice" type="number" clearable>
              <template slot="prepend">销售价</template>
            </el-input>
          </div>
        </el-form-item>
        <!-- <el-form-item label="库存设置">
          <div class="flex" style="grid-template-columns: repeat(2,1fr);">
            <el-input type="number" v-model="rule.storeAverageUseCount" clearable>
              <template slot="prepend">单店用量</template>
            </el-input>
            <el-input type="number" v-model="rule.storeInventoryCount" clearable>
              <template slot="prepend">预警店铺数量</template>
            </el-input>
          </div>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMaterialDetail">取 消</el-button>
        <el-button type="primary" @click="sendMaterailInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { mapGetters } from "vuex";
import quinn from "@/utils/quinn";
import tableMixins from "@/mixins/tableMixins.vue";
import * as Ray from '../../utils/public'
import { forEach } from "lodash";
import { max } from "lodash";
import * as XLSX from 'xlsx'
export default {
  name: "MaterialList",
  mixins: [tableMixins],
  meta: { title: "材料列表", icon: "el-icon-s-data", sort: 2,authority: 103 },
  data() {
    return {
      apiName: "classificationMaterialList",
      userName:'',
      openMateStatuts: false,
      loading:false,
      isUpdate: false,
      material: {
        list: [],
        pageNumber: 1,
        pageSize: 20,
        currentPage: 1,
        count: 0,
        cateUpdateVisible: false,
        cateId: '',
        cateUpdateValue: ''
      },
      supplierList: [],
      type: 'add',
      rule: {
        classificationId: '',
        supplierId: '',
        color: '',
        createdAt: '',
        materialId: '',
        materialName: '',
        norm: '',
        price: '',
        salePrice: '',
        status: '',
        categoryName: '',
        categoryId:'',
        supplierId:'',
        supplierName: '',
        supplier: {
          supplierId: '',
          supplierName: '',
        },
        storeAverageUseCount: '',
        storeInventoryCount: '',
      },
      rules: {
        materialName: [
          { required: true, message: '请输入材料名称', trigger: 'blur' }
        ],
      },
      searchCateList:[],
      maxHeight:'',
      category: {
        list: [],
        cateVisible: false,
        createCateValue: '',
        count: 0,
        selectValue: '',
        pageNumber: 1,
        pageSize: 5,
        currentPage: 1
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize =()=>{
      this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    }
  },
  created() {
    const { userName = [] } =
            quinn.getStorage("userDatav3") || store.state.userData || {};
        this.userName = userName;
    this.getMaterial();
    this.getCategory();
    this.getSupplier();
    this.searchCategory();
    // this.searchCateInfo();
  },
  methods: {
    deleteMaterail(info){
      this.$api.materialMaterialDelete({'materialId':info.materialId}).then(res=>{
        this.getMaterial();
      })
    },
    updateMaterialDownload(){
      this.$api.materialMaterialList({pageNumber:1,pageSize:100000000}).then(res=>{
        let info = res.rows;
      console.log(info,'info')
      //   const headerArr = ['procureId', 'orderName', 'createdAt', 'materialTotalPrice', 'materials', 'balancePayment', 'supplierName', 'warehouse', 'remark']
      // const newHeaderArr = ['采购单号', '采购单名称', '发起日期', '总价', '材料明细', '未付金额', '供应商', '仓库', '备注']

        const headerArr = ['materialId']
      const newHeaderArr = ['材料编码']
      // 把对象数组转换成工作表，表头顺序按照headerArr的顺序
      const ws = XLSX.utils.json_to_sheet([info], { header: headerArr })
      // 创建新的工作簿，0.20.1版本的sheetJs可以支持传参，但当前使用的是0.18.5版本，不支持传参
      const wb = XLSX.utils.book_new();
      // 把第一行的表头(newHeaderArr )替换成实际需要展示的表头
      XLSX.utils.sheet_add_aoa(ws, [newHeaderArr], { origin: "A1" });
      // 将生成的工作表添加到新的工作簿里，Sheet1是工作表的名称
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      // 下载工作簿
      XLSX.writeFile(wb, info.createdAt + '-' + new Date().getTime() + ".xlsx");

      })
    },
    cateClose(){
    this.category.cateVisible= false;
    this.category.createCateValue = ''
    this.getMaterial();
    },
    closeMaterialDetail(){
      this.rule = {};
      this.openMateStatuts = false
    },
    getSupplier() {
      this.$api.supplierSupplierList({ pageSize: 300 ,pageNumber:1}).then(res => {
        this.supplierList = res.rows;
      })
    },
    getCategory() {
      let params = {
        pageNumber: this.category.pageNumber,
        pageSize: this.category.pageSize
      }
      this.$api.classificationClassificationList(params).then(res => {
        res.rows.map((e) => {
          if (e.createdAt) e.createdTime = dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss");
        })
        this.category.count = res.count;
        this.category.list= res.rows;
      })
    },

    searchCategory(){
      this.$api.classificationClassificationList({pageSize:300,pageNumber:1}).then(res => {
      //  this.category.list = res.rows;
      this.searchCateList= res.rows;
      })
    },
    // searchCateInfo(){
    //   let params={
    //     pageSize: 5,
    //     pageNumber:1,
    //     ids:this.category.selectValue
    //   }
    //   this.$api.classificationClassificationList(params).then(res => {
    //    this.category.list = res.rows;
    //   })
    // },
    createCateSend() {
      this.$api.classificationClassificationAdd({
        'name': this.category.createCateValue
      }).then(res => {
        this.getCategory();
        this.getMaterial();
      })
    },
    deleteCate(info) {
      this.$api.classificationClassificationDelete({ 'classificationId': info.classificationId }).then(res => {
        this.getCategory()
        this.getMaterial();
      })
    },
    createCate() {
      this.getCategory();
      this.category.cateVisible = true;
    },
    eidtCate(ite) {
      this.material.cateUpdateVisible = true;
      this.material.cateUpdateValue = ite.name;
      this.material.cateId = ite.classificationId;
    },
    sendEditCate() {
      let params = {
        name: this.material.cateUpdateValue,
        classificationId: this.material.cateId
      }
      this.$api.classificationClassificationUpdate(params).then(res => {
        this.material.cateUpdateVisible = false;
        this.getMaterial();
      })
    },
    handleCateSizeChange(val) {
      this.category.pageSize = val;
      this.getCategory();
    },
    handleCateCurrentChange(val) {
      this.category.pageNumber = val;
      this.getCategory();
    },
    // 获取分类下的材料
    getMaterial() {
      this.loading= true;
      setTimeout(()=>{
      let params = {
        pageNumber: this.material.pageNumber,
        pageSize: this.material.pageSize
      }
      this.$api.classificationMaterialList(params).then(res => {

        res.rows.map(e => {
          e.storeCount = 0
          e.supplierList = [];
          e.createdAt = dayjs(e.createdAt).format('YYYY-MM-DD hh:mm:ss')
          if (e.materials.length > 0) {
            e.materials.map((el,index) => {

              if(index == 0){
                e.largeUnit =el.unit;
              }
              e.supplierList.push(el.supplier.supplierName + ' / ');
              if(el.totalCount > 0){
                e.storeCount +=  Math.floor(el.totalCount / el.storeAverageUseCount);
              }
            })
            e.supplierList.join(',')
            e.supplierList = Ray.duplicate(e.supplierList);
            e.supplierList[e.supplierList.length-1] = e.supplierList[e.supplierList.length-1].split(' / ').join('')
          }
          if (e.createdAt) e.createdTime = dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss");
        })
        this.material.list = res.rows;
        this.material.count = res.count;
        this.loading = false;
      })
      },100)
    },
    editCateSelect(e) {
      this.rule.classificationId = e;
    },
    editSupplierSelect(e) {
      this.rule.supplierId = e;
    },
    handleMateSizeChange(val) {
      this.material.pageSize = val;
      this.getMaterial();
    },
    handleMateCurrentChange(val) {
      this.material.pageNumber = val;
      this.getMaterial();
    },
    edifMaterail(type, info) {
      this.rule ={};
      this.openMateStatuts = true;
      this.type = type
      if (type == 'update') {
        this.isUpdate = true;
        this.rule = { ...info };
        this.rule.supplierId =info.supplier.supplierId;
        this.rule.classificationId = info.classificationId

      } else if (type == 'add') {
        this.isUpdate = false;
      }
    },
    sendMaterailInfo() {
      let info = {
        materialName: this.rule.materialName,
        materialId: this.rule.materialId,
        norm: this.rule.norm,
        color: this.rule.color,
        unit: this.rule.unit,
        price: this.rule.price,
        salePrice: this.rule.salePrice,
        storeAverageUseCount: this.rule.storeAverageUseCount,
        storeInventoryCount: this.rule.storeInventoryCount,
        supplierId: this.rule.supplierId,
        classificationId: this.rule.classificationId,
        limit: 15
      }

      if (this.type == 'add') {
        for(let k in info){
        if(info[k] == ''){
          this.$message({
              message: '请完善表单信息!',
              type: 'error'
            });
            return
        }
      }
        this.$api.materialMaterialAdd(info);
      } else if (this.type = 'update') {
        this.$api.materialMaterialUpdate(info);
      }
      this.openMateStatuts = false;
      this.getMaterial();
      this.getCategory();
    }


  },
};
</script>

<style lang="less" scoped>
.search {
  display: flex;
  align-items: center;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.mainTable {
  margin: 10px 0;
}

.flex {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}

.default /deep/ .el-button {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

/deep/ .el-button:hover {
  color: black;
  border-color: #DCDFE6;
  background-color: white;
}

span /deep/ .el-button:nth-child(2) {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

span /deep/ .el-button:nth-child(2):hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}
// .main /deep/ .el-select:hover{
//   border-color:#ff6a00 !important;
// }
//  /deep/ .el-input__inner{
//   border-color: #ff6a00 !important;
// }
/deep/ .el-input__inner:hover{
  border-color: #ff6a00 !important;
}
/deep/ .el-input__inner:focus{
  border-color: #ff6a00 !important;
}
/deep/ .selected{
  color:#ff6a00 !important;
}
/deep/ .active{
  color:#ff6a00 !important;
}
/deep/ .selected{
  color:#ff6a00 !important;
}
/deep/ .el-loading-text{
  color:#ff6a00 !important;
}
/deep/ .el-icon-loading{
  color:#ff6a00 !important;
}
</style>
